package com.xq.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.google.gson.GsonBuilder;
import com.jfinal.aop.Before;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.xq.common.Constants;
import com.xq.common.utils.XiaoQuUtils;
import com.xq.model.LoginToken;
import com.xq.model.User;
import com.xq.model.XiaoQu;

public class UserController extends BaseController {
	
	private static Logger logger = Logger.getLogger(UserController.class);
	
	public void login()
	{
		XQResponse response = null;
		String phone = StringUtils.trim(getPara("phone"));
		String password = StringUtils.trim(getPara("password"));
		User user = null;
		try {
			user = User.dao.findUserByPhone(Long.valueOf(phone));
		} catch (Exception e) 
		{
		}
		
		if (user == null || !password.equals(user.get("password")))
		{
			response = new XQResponse(XQResponse.STATUS_PASSWORD_AND_PHONE_MISMATCH);
		} else {
			
			Map<String, Object> context = user.cloneAttrs();
			
			int xiqoQuId = user.getInt("xiaoQuId");
			XiaoQu xiaoQu = XiaoQu.dao.findById(xiqoQuId);
			
			String token = UUID.randomUUID().toString();
			LoginToken loginToken = new LoginToken();
			loginToken.set("userId", user.get("id"));
			loginToken.set("token", token);
			loginToken.set("createDate", new Date());
			loginToken.save();
			
			context.put("xiaoqu", xiaoQu.cloneAttrs());
			context.put("token", loginToken.cloneAttrs());
			
			response = new XQResponse(XQResponse.STATUS_SUCCESS
					, "success", new GsonBuilder()
			.registerTypeAdapter(Integer.class, new GsonNumberToStringAdaptor())
			.registerTypeAdapter(Long.class, new GsonNumberToStringAdaptor())
			.setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(context));
		}
		renderJson(response);
	}
	
	@Before(Tx.class)
	public void register()
	{
		UploadFile portraitUploadFile = this.getFile("portrait");
		long phone = getParaToLong("phone");//required
		String password = getPara("password");
		String nick = getPara("nick");
		
		String xiaoQuName = getPara("xiaoqu");//required
		int unit = getParaToInt("unit");//required
		int room = getParaToInt("room"); //required
		
		XiaoQu xiaoQu = XiaoQu.dao.findByName(xiaoQuName);
		//表示用户手动输入的小区，并且系统目前小区信息。
		//所以先创建小区，但是不知道的小区经度纬度(暂且随便给一个经度纬度)
		if (xiaoQu == null)
		{
			xiaoQu = new XiaoQu();
			xiaoQu.set("name", xiaoQuName);
			xiaoQu.set("longitude", new Double(121.241256));
			xiaoQu.set("latitude", new Double(31.066875));//随便给的地址
			xiaoQu.set("createdBy", 2);//2 表示用户创建的小区
			xiaoQu.save();
		}
		Integer xiaoQuId = (Integer)xiaoQu.get("id");
		if (User.dao.isPhoneRegistered(phone))
		{
			XQResponse resonse = new XQResponse(XQResponse.STATUS_PHONE_ALREADY_REGISITERED);
			renderJson(resonse);
			return;
		}
		User user = new User();
		user.set("phone", phone);
		user.set("password", password);
		user.set("nick", nick);
		user.set("xiaoQuId", xiaoQuId);
		user.set("unit", unit);
		user.set("room", room);
		user.set("registerDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		user.save();
		
		try {
			String portraitFile = user.getInt("id") + "." + XiaoQuUtils.getFileExtension(portraitUploadFile.getFileName());
			String destFilePath = 
					Constants.USER_PORTRAIT_PATH + File.separator + portraitFile;
			logger.debug("user portrait destination path:" + destFilePath);
			FileUtils.moveFile(portraitUploadFile.getFile(), new File(destFilePath));
			user.set("portrait", portraitFile);
		} catch (IOException e) {
			logger.debug("move file error", e);
		}
		user.update();
		XQResponse response = new XQResponse(XQResponse.STATUS_SUCCESS
				, "success", new GsonBuilder()
		.registerTypeAdapter(Integer.class, new GsonNumberToStringAdaptor())
		.registerTypeAdapter(Long.class, new GsonNumberToStringAdaptor())
		.create()
		.toJson(user.cloneAttrs()));
		renderJson(response);
	}
	
	public void uploadPortrait()
	{
		UploadFile uploadImage = getFile();
		long phone = getParaToLong("phone");
		try {
			FileUtils.moveFile(uploadImage.getFile(), new File("/"));
		} catch (IOException e) {
			logger.debug("move file error", e);
		}
	}
	
}
